package com.example.campus.utils;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import io.minio.errors.MinioException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Data
@AllArgsConstructor
@Slf4j
public class MinIOUtil {
    private String endpoint;
    private String accessKey;
    private String secretKey;
    private String bucketName;


    /**
     * 文件上传
     *
     * @param bytes
     * @param objectName
     * @return
     */
    public String upload(byte[] bytes, String objectName, String imageType) {
        //创建 MinioClient 实例
        MinioClient minioClient = MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();

        try {
            objectName = imageType + "/" + objectName;
            //创建 PutObjectArgs 请求
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .stream(new ByteArrayInputStream(bytes), bytes.length, -1)
                    .build();
            //执行上传操作
            minioClient.putObject(putObjectArgs);
        } catch (MinioException | IOException | NoSuchAlgorithmException | InvalidKeyException e) {
            System.out.println("文件上传失败: " + e.getMessage());
        }


        StringBuilder stringBuilder = new StringBuilder(endpoint);
        stringBuilder
                .append("/")
                .append(bucketName)
                .append("/")
                .append(objectName);

        log.info("文件上传到:{}", stringBuilder.toString());

        return stringBuilder.toString();
    }

    /**
     * 从 MinIO 删除图片
     *
     * @param objectName 要删除的对象名称
     * @return 删除操作是否成功
     */
    public boolean deleteObject(String objectName) {
        // 创建 MinioClient 实例
        MinioClient minioClient = MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();

        try {
            // 创建 RemoveObjectArgs 请求
            RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .build();
            // 执行删除操作
            minioClient.removeObject(removeObjectArgs);
            log.info("成功从 MinIO 删除对象: {}", objectName);
            return true;
        } catch (MinioException | IOException | NoSuchAlgorithmException | InvalidKeyException e) {
            log.error("从 MinIO 删除对象失败: {}", objectName, e);
            return false;
        }
    }
}
